import request from '../uview-ui/libs/request/index.js'

class Login {
	code
	
	checkPhoneData() {
		let phoneData = uni.getStorageSync('phoneData')
		if (!phoneData.account_phone) {
			return false
		}
		return true
	}
	
	async startLogin(info, initState = true) {
		// #ifdef MP-WEIXIN
		let resCode = await uni.login()
		uni.setStorageSync('code', resCode[1].code)
		this.code = resCode[1].code
		debugger
		//执行登陆
		await this.getUserToken(info, initState)
		// #endif
	}
	
	// 登陆逻辑
	async getUserToken(info, initState = true) {
		// #ifdef MP-WEIXIN
		let postData = {
			code: this.code,
			nick_name: info.nickName,
			avatar_url: info.avatarUrl,
			sex: info.gender,
		}
		let resToken = await request.post('/logins', postData).catch(e => {
	    console.log(e)
			return uni.showToast({
				title: '登陆失败',
				icon: 'error',
				duration: 2000
			})
	  })
	  if(resToken) {
			uni.setStorageSync('userInfo', info)
	    uni.setStorageSync('token', resToken.data.token)
		  console.log('登录token：', resToken.data.token)
			uni.showToast({
				title: '登陆成功',
				icon: 'success',
				success: () => {
					if (initState) {
						setTimeout(() => {
							uni.$emit('refresh')
						}, 1500)
					}
				}
			})
	  }
		// #endif
	}
	bindPhone(encryptedData, iv) {
		return request.post('/phones', {
			encryptedData,
			iv
		})
	}
}

export default new Login()